//
//  PictureSelectorViewController.swift
//  sinaOnceAgain
//
//  Created by 王相超 on 16/2/26.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit

private let pictureSelectCellId = "pictureSelectCell"

private let coloumCount: CGFloat = 3

private let maxImageCount = 3

class PictureSelectorViewController: UICollectionViewController {
    
    
      //定义图片数组
    lazy var imageList = [UIImage]()

       //构造函数
    init () {
        
        let layout = UICollectionViewFlowLayout()
        
        //计算cell的宽度
        let w = (ScreenWidth - (coloumCount + 1) * PictureCellMargin) / coloumCount
        
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.minimumLineSpacing = PictureCellMargin
        
        //设置组间距
        layout.sectionInset = UIEdgeInsetsMake(PictureCellMargin, PictureCellMargin, 0, PictureCellMargin)
        
        //必须调用指定的构造函数
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView?.registerClass(PictureSelectCell.self, forCellWithReuseIdentifier: pictureSelectCellId)
    }

}

extension PictureSelectorViewController {
    
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        //操作数据源本身 到达添加数据的效果
        let detla = imageList.count == maxImageCount ? 0 : 1
        
        return imageList.count + detla
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureSelectCellId, forIndexPath: indexPath) as! PictureSelectCell
        
        cell.backgroundColor = UIColor.randomColor()
        //指定代理
        cell.delegate = self
        
        //设置cell的图片
        //imageList.count == indexPath.item  最后一个cell
        if imageList.count == indexPath.item {
            
            //显示多余出来的那一条数据
            cell.image = nil
        }else{
            
            //数组内的数据
            cell.image = imageList[indexPath.item]
        }
        
        
        
        return cell
        
    }
}

extension PictureSelectorViewController: PictureSelectCellDelegate {
    
    //选择图片
    func userWillChosePicture() {
        
        //选择图片使用imagePicker  UIImagePickerController 调用系统相册
        let picker = UIImagePickerController()
        
        //如果需要对获取的数据进行操作 需要设置代理  并且实现协议方法
        picker.delegate = self
        
        //如果希望有编辑信息
       // picker.allowsEditing = true
        
        presentViewController(picker, animated: true, completion: nil)
    }
    
    //删除图片
    func userWillDeletePicture(cell: PictureSelectCell) {
        
        //在数据源中删除数据
        //确定点击的cell 对应的indexPath
        if let indexPath = collectionView?.indexPathForCell(cell) {
            
            imageList.removeAtIndex(indexPath.item)
            
            collectionView?.reloadData()
            
        }
        
    }
}


//实现UIImagePickerControllerDelegate
extension PictureSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //添加图片到数组中
        imageList.append(image)
        
        //刷新collectionView
        collectionView?.reloadData()
        
        //dismiss页面
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}


//声明 自定义的 协议
protocol PictureSelectCellDelegate: NSObjectProtocol {
    
    //声明协议方法
    func userWillChosePicture()
    
    func userWillDeletePicture(cell: PictureSelectCell)
}


//MARK: 自定义cell

 class PictureSelectCell: UICollectionViewCell {
    
    
    //外界设置的图片属性
    var image: UIImage? {
        
        didSet{
            deleteBtn.hidden = image == nil
            //给 addBtn设置图片
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    //声明代理对象
    weak var delegate: PictureSelectCellDelegate?
    
    //添加的监听方法
    @objc private func addBtnClick() {
        
        if self.image != nil{
            return
        }
        
        //调用协议方法
        delegate?.userWillChosePicture()
    }
    
    @objc private func deleteBtnClick() {
        
        //调用协议方法
        delegate?.userWillDeletePicture(self)
    }
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor(white: 0.95, alpha: 1)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
        
        //添加子视图
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(contentView.snp_top)
        }
        
        //设置按钮的视图显示样式   本身按钮的显示式样
        addBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        //添加点击事件
        addBtn.addTarget(self, action: "addBtnClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnClick", forControlEvents: .TouchUpInside)
        
    }
    
    
    //懒加载视图
    private lazy var addBtn: UIButton = UIButton(backImageName: "compose_pic_add", imageName: nil)
    private lazy var deleteBtn: UIButton = UIButton(backImageName: nil, imageName: "compose_photo_close")
}





